package com.zyh.block;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @Author zyh
 * @Date 2024/8/9 14:28
 * @Description 阻塞队列
 * ArrayBlockQueue
 */

public class ArrayBlockQueueDemo {
    public static void main(String[] args) {
        //创建ArrayBlockQueue队列
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
        //开启生产者线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "开始生产");
                //循环10次存入queue中
                for (int i = 0; i < 10; i++) {
                    //模拟存数据的时间
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    queue.offer(i);
                    System.out.println(Thread.currentThread().getName() + "生产了" + i);
                }
            }
        }, "生产者A").start();
        //开启消费者线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("消费者开始消费");
                //死循环一直取数据
                while (true) {
                    try {
                        Thread.sleep(200);
                        Integer take = queue.take();
                        System.out.println(Thread.currentThread().getName() + "消费了" + take);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "消费者A").start();
    }
}
